package com.company.beauty.common.handler;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * <p>日志拦截器</p>
 *
 * @author Lionel Lee
 * @version 1.0: LoggingRequestInterceptor.java
 * @date 2023/1/2 09:53
 */
@Slf4j
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
    /**
     * 用来记录接口执行时间的最小接收值
     */
    private final long timeoutMs;

    public LoggingRequestInterceptor(long timeoutMs) {
        this.timeoutMs = timeoutMs;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {

        Stopwatch stopwatch = Stopwatch.createStarted();
        ClientHttpResponse response = execution.execute(request, body);
        stopwatch.stop();
        long cost = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        if (cost > timeoutMs) {
            log.warn("Request uri: [{}], Cost times: {}ms", request.getURI(), cost);
        }
        // 打印日志
        trace(request, body, response);
        return response;
    }

    private void trace(HttpRequest request, byte[] body,
                       ClientHttpResponse response) throws IOException {
        // 记录日志
        String responseStr = IOUtils.toString(response.getBody(), StandardCharsets.UTF_8);
        log.info("\n" + "URI          : {}, \n" + "Method       : {}, \n" + "Headers      : {}, \n"
                 + "Param        : {}, \n" + "RespStatus   : {}, \n" + "Response     : {}",
            request.getURI(), request.getMethod(), request.getHeaders(),
            new String(body, StandardCharsets.UTF_8), response.getStatusCode(), responseStr);
    }
}
